import java.util.concurrent.*;

/**
 * @author dsp
 * @date 2021-04-11
 */
public class GetThreadResult {

    public static final InheritableThreadLocal<Result> local = new InheritableThreadLocal<>();
    volatile int num = 0;

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Result result = new Result();
        RunnableTask runnableTask = new RunnableTask(result);
        CallableTask callableTask = new CallableTask(result);

        // 1 Runnable while
        // Thread thread = new Thread(runnableTask);
        // thread.start();
        // while (result.getName() == null) {
        //     Thread.sleep(1000);
        // }
        // System.out.println(result.getName());

        // 2 Runnable join
        // Thread thread = new Thread(runnableTask);
        // thread.start();
        // thread.join();
        // System.out.println(result.getName());

        // 3 Callable,使用Thread
        // FutureTask<Result> task = new FutureTask<>(callableTask);
        // Thread t = new Thread(task);
        // t.start();
        // System.out.println(task.get().getName());

        // 4 Callable,创建线程池
        // ExecutorService service = Executors.newFixedThreadPool(1);
        // Future<Result> future = service.submit(callableTask);
        // System.out.println(future.get().getName());

        // 5 InheritableThreadLocal
        // local.set(result);
        // Thread thread = new Thread(() -> local.get().setName("dd"));
        // thread.start();
        // while (local.get().getName() == null){
        //     Thread.sleep(1000);
        // }
        // System.out.println(local.get().getName());

        // 6 volatile
        // GetThreadResult getThreadResult = new GetThreadResult();
        // Thread thread = new Thread(new Runnable() {
        //     @Override
        //     public void run() {
        //         result.setName("dd");
        //         getThreadResult.add();
        //     }
        // });
        // thread.start();
        // while (getThreadResult.getNum()<1){
        //     Thread.sleep(1000);
        // }
        // System.out.println(result.getName());

    }

    public void add(){
        num++;
    }

    public int getNum() {
        return num;
    }

    static class CallableTask implements Callable<Result> {

        private Result result;

        @Override
        public Result call() throws Exception {
            result.setName("dd");
            return result;
        }

        public CallableTask(Result result) {
            this.result = result;
        }
    }

    static class RunnableTask implements Runnable {

        private Result result;

        public RunnableTask(Result result) {
            this.result = result;
        }

        @Override
        public void run() {
            result.setName("dd");
        }
    }
}
